package dao

import (
	"github.com/micro/go-micro/v2/errors"
	wechat "micro-grpc-server/services/wechat/proto"
)

// 获取微信用户标签
func (d *WechatDao) Tags(scenario string) ([]*wechat.Tag, error) {
	var tags []*wechat.Tag
	var mp = d.GetMp(scenario)
	if mp == nil {
		return tags, errors.BadRequest(d.conf.ServerName, "%s 配置不存在", scenario)
	}

	wechatTags, err := mp.GetUser().GetTag()
	if err != nil {
		return tags, err
	}
	tags = make([]*wechat.Tag, len(wechatTags)+1)
	var total int64

	for index, tag := range wechatTags {
		total += tag.Count
		tags[index+1] = &wechat.Tag{
			Name:  tag.Name,
			Count: tag.Count,
			Id:    tag.ID,
		}
	}

	// 需要一个全部
	tags[0] = &wechat.Tag{
		Name:  "全部",
		Count: total,
		Id:    0,
	}

	return tags, nil
}

// 给用户打标签
func (d *WechatDao) BatchTag(scenario string, userList []string, tagId int32) error {
	var mp = d.GetMp(scenario)
	if mp == nil {
		return errors.BadRequest(d.conf.ServerName, "%s 配置不存在", scenario)
	}
	users, err := d.FindListByUserList(scenario, userList)
	if err != nil {
		return errors.BadRequest(d.conf.ServerName, err.Error())
	}
	if len(users) == 0 {
		return nil
	}
	var openidList []string
	for _, u := range users {
		openidList = append(openidList, u.Openid)
	}

	return mp.GetUser().BatchTag(openidList, tagId)
}

// 给用户取消标签
func (d *WechatDao) BatchUnTag(scenario string, userList []string, tagId int32) error {
	var mp = d.GetMp(scenario)
	if mp == nil {
		return errors.BadRequest(d.conf.ServerName, "%s 配置不存在", scenario)
	}
	users, err := d.FindListByUserList(scenario, userList)
	if err != nil {
		return errors.BadRequest(d.conf.ServerName, err.Error())
	}
	if len(users) == 0 {
		return nil
	}
	var openidList []string
	for _, u := range users {
		openidList = append(openidList, u.Openid)
	}

	return mp.GetUser().BatchUntag(openidList, tagId)
}
